#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <string.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
	int sockfd;
	struct sockaddr_in addr;
	char buf[512] = {0};
	int i;
	for(i=0;i<512;i++)
	{	int index = 0;
		buf[i] = ('a'+index);
		if(index>('z'-'a'))
			index = '0';
	}
	buf[511] = '\0';
	memset((void*)&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(11112);
	inet_pton(AF_INET, "192.168.241.133", &addr.sin_addr);
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd==-1)
	{
		printf("create socket error!\n");
		exit(1);
	}

	if(connect(sockfd, (struct sockaddr*)&addr, sizeof(addr))==-1)
	{
		printf("connect error!\n");
		close(sockfd);
		exit(1);
	}

	printf("connect successfully\n");
	int total = 0;
	getchar();
	int status = fcntl(sockfd, F_GETFL, 0);
	status |= O_NONBLOCK;
	fcntl(sockfd, F_SETFL, status);
	status = fcntl(sockfd, F_GETFL, 0);
	if(status&O_NONBLOCK)
		printf("the socket is non block!\n");
	else
		printf("the socket is block!\n");
	while(1)
	{
		printf("start to send,total send:%d\n", total);
		ssize_t sendnum = write(sockfd, (void*)buf, 512);
		usleep(10000);
		if(total==5120)
			getchar();
		printf("once send %ld bytes\n", sendnum);
		if(sendnum>0)
			total += sendnum;
		else if(sendnum==-1)
		{
			//break by signal
			if(errno==EINTR)
				continue;
			//buffer is full
			else if(errno==EAGAIN)
			{
				printf("buffer is full!\n");
				getchar();
				continue;
			}
			//error
			else if(errno==EBADF)
			{
				printf("send error! have send %d bytes\n", total);
				exit(1);
			}

		}
		else if(sendnum==0)
		{
			printf("disconnect!\n");
			getchar();
			exit(1);
		}
		else
		{
			printf("unknow error!\n");
			exit(1);
		}
	}
	return 0;
}
